package com.titaniume.exer;

import org.junit.Test;

/**
 *@program: JavaSenior
 *@description:
 *@author: renfei.huang
 *@create: 2021-10-08 08:25
 */
public class StringDemo1 {

    /*
     获取一个字符串在另一个字符串中出现的次数。
     比如：获取“ ab”在 “abkkcadkabkebfkabkskab” 中出现的次数
     */


    //获取subStr 在mainStr中出现的次数
//    ab kkcadkabkebfkabkskab  0 2
//    kkcadkab kebfkabkskab  6 8
//    kebfkabkskab  5 7
//    kskab  3 5
    public int getCount(String mainStr,String subStr){
        int mainLength = mainStr.length();
        int subLength = subStr.length();
        int count = 0;
        int index = 0;
        if(mainLength > subLength){
            //方式一：
            while ((index = mainStr.indexOf(subStr))!=-1){
                count ++;
                //substring 左闭右开
                mainStr = mainStr.substring(index + subStr.length());
            }
            return count;
        }else{
            return 0;
        }
    }

    //0
    //8
    //15
    //20
    //indexOf(String str, int fromIndex)
    //返回指定子串的第一次出现的字符串中的索引，从指定的索引开始。
    public int getCount2(String mainStr,String subStr){
        int mainLength = mainStr.length();
        int subLength = subStr.length();
        int count = 0;
        int index = 0;
        if(mainLength > subLength){
            //方式二：
            // ab 0
            // ab 8
            // ab 15
            // ab 20
            //每次在前一个ab的索引基础上查找
            while ((index = mainStr.indexOf(subStr,index))!=-1){
                count ++;
                index+= subLength;
            }
            return count;
        }else{
            return 0;
        }
    }

    @Test
    public void testCount(){
        String mainStr ="abkkcadkabkebfkabkskab";
        String subStr ="ab";
        int count = getCount(mainStr, subStr);
        System.out.println(subStr+"出现次数:"+ count);


        int count2 = getCount2(mainStr, subStr);
        System.out.println(subStr+"出现次数:"+ count2);
    }

    @Test
    public  void test1(){
        String mainStr ="abkkcadkabkebfkabkskab";
        String subStr ="ab";
//        int index = 2;
        int index = 20;
        System.out.println(mainStr.indexOf(subStr,index));

    }


}
